<template>
	<!-- 模板内容保持不变 -->
	<div class="min-h-screen bg-gradient-to-br from-gray-50 via-blue-50 to-indigo-50">
		<!-- 背景装饰 -->
		<div class="fixed inset-0 overflow-hidden pointer-events-none">
			<div
				class="absolute -top-40 -right-40 w-80 h-80 bg-blue-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob">
			</div>
			<div
				class="absolute -bottom-40 -left-40 w-80 h-80 bg-purple-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000">
			</div>
			<div
				class="absolute top-40 left-40 w-80 h-80 bg-pink-200 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000">
			</div>
		</div>

		<!-- 主要内容区域 -->
		<div class="container mx-auto px-12 py-10 pt-32 relative z-10">
			<!-- 顶部：返回与标题 -->
			<div class="flex items-center justify-between mb-10">
				<div class="flex items-center gap-4">
					<el-button type="primary" link @click="goBack" class="text-gray-600 hover:text-gray-800 text-lg">
						<el-icon class="mr-2 text-xl">
							<ArrowLeft />
						</el-icon>
						返回班级列表
					</el-button>
					<h1 class="text-4xl font-bold text-gray-900">{{ classInfo?.className || '班级详情' }}</h1>
				</div>
				<div class="text-lg text-gray-600 font-medium">{{ currentWeekRange }}</div>
			</div>

			<!-- 主体布局 -->
			<div class="grid grid-cols-1 lg:grid-cols-3 gap-10">
				<!-- 左侧：班级信息 -->
				<div class="lg:col-span-1">
					<div
						class="bg-white rounded-3xl shadow-xl border border-gray-200 p-8 sticky top-32 h-full min-h-[calc(100vh-8rem)] flex flex-col relative">
						<!-- 班级头像和基本信息 -->
						<div class="p-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-2xl mb-8">
							<div class="flex items-center gap-6">
								<div
									class="w-28 h-28 bg-white bg-opacity-20 rounded-2xl flex items-center justify-center shadow-lg">
									<span
										class="text-white text-6xl font-bold select-none leading-none">{{ getFirstChar(classInfo?.className) }}</span>
								</div>
								<div class="text-white">
									<h2 class="text-3xl font-bold mb-3">{{ classInfo?.className }}</h2>
									<p class="text-blue-100 text-lg">{{ classInfo?.grade }}</p>
								</div>
							</div>
						</div>

						<!-- 班级详细信息 -->
						<div class="space-y-8 pb-28">
							<!-- 基本信息 -->
							<div class="space-y-6">
								<div class="flex items-center gap-5">
									<div class="w-16 h-16 bg-blue-100 rounded-xl flex items-center justify-center">
										<el-icon class="text-blue-600 text-2xl">
											<User />
										</el-icon>
									</div>
									<div>
										<p class="text-lg text-gray-500 mb-2">授课教师</p>
										<p class="text-xl font-semibold text-gray-900">
											{{ classInfo?.teacherName || '陈老师' }}
										</p>
									</div>
								</div>
								<div class="flex items-center gap-5">
									<div class="w-16 h-16 bg-green-100 rounded-xl flex items-center justify-center">
										<el-icon class="text-green-600 text-2xl">
											<UserFilled />
										</el-icon>
									</div>
									<div>
										<p class="text-lg text-gray-500 mb-2">班级人数</p>
										<p class="text-xl font-semibold text-gray-900">
											{{ classInfo?.studentCount || 0 }}人
										</p>
									</div>
								</div>
							</div>

							<!-- 班级统计 -->
							<div class="pt-8 border-t border-gray-200">
								<h4 class="text-xl font-semibold text-gray-700 mb-6">班级统计</h4>
								<div class="grid grid-cols-2 gap-6">
									<div
										class="bg-blue-50 rounded-2xl p-6 text-center h-24 flex flex-col justify-center">
										<div class="text-3xl font-bold text-blue-600">{{ classInfo?.studentCount || 0 }}
										</div>
										<div class="text-base text-blue-500">总人数</div>
									</div>
									<div
										class="bg-green-50 rounded-2xl p-6 text-center h-24 flex flex-col justify-center">
										<div class="text-3xl font-bold text-green-600">{{ courseCount }}</div>
										<div class="text-base text-green-500">课程数</div>
									</div>
								</div>
							</div>

							<!-- 班级描述 -->
							<div class="pt-8 border-t border-gray-200">
								<h4 class="text-xl font-semibold text-gray-700 mb-4">班级描述</h4>
								<p class="text-gray-700 leading-relaxed text-lg">
									{{ classInfo?.description || '该班级暂无描述。' }}
								</p>
							</div>

							<!-- 螺旋向上的动态图 -->
							<div class="mt-6 flex justify-center">
								<div class="helix-container">
									<div class="helix-row" v-for="n in 10" :key="n" :style="{ '--i': n }">
										<span class="helix-dot left"></span>
										<span class="helix-dot right"></span>
									</div>
								</div>
							</div>

							<div class="flex-1"></div>

							<!-- 快捷操作 -->
							<div class="absolute bottom-8 left-8 right-8 pt-6 border-t border-gray-200">
								<h4 class="text-xl font-semibold text-gray-700 mb-6">快捷操作</h4>
								<div class="space-y-4">
									<button @click="goToStudy"
										class="w-full h-16 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-medium text-lg rounded-2xl flex items-center justify-center gap-3 transition-all shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]">
										<el-icon class="text-2xl">
											<Reading />
										</el-icon>
										开始学习
									</button>
									<button @click="goToResources"
										class="w-full h-16 bg-gradient-to-r from-gray-500 to-gray-600 hover:from-gray-600 hover:to-gray-700 text-white font-medium text-lg rounded-2xl flex items-center justify-center gap-3 transition-all shadow-lg hover:shadow-xl transform hover:scale-[1.02] active:scale-[0.98]">
										<el-icon class="text-2xl">
											<Files />
										</el-icon>
										查看资源
									</button>
								</div>
							</div>
						</div>
					</div>
				</div>

				<!-- 右侧：课程安排与任务 -->
				<div class="lg:col-span-2 space-y-8">
					<!-- 课程安排 -->
					<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
						<div class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
							<div class="flex items-center justify-between">
								<div class="flex items-center gap-4">
									<div
										class="w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center">
										<el-icon class="text-white text-2xl">
											<Calendar />
										</el-icon>
									</div>
									<div>
										<h3 class="text-3xl font-bold text-gray-900 mb-2">课程安排</h3>
										<p class="text-blue-600 font-medium text-xl">{{ currentWeekRange }}</p>
									</div>
								</div>
								<div class="flex items-center gap-3">
									<el-button type="primary" size="large" :disabled="currentWeek <= 1"
										@click="prevWeek" class="rounded-full px-6 hover:shadow-md transition-shadow">
										<el-icon class="mr-2">
											<ArrowLeft />
										</el-icon>上一周
									</el-button>
									<div class="bg-white px-6 py-3 rounded-full shadow-sm border border-blue-200">
										<span class="text-lg text-blue-600 font-semibold">第{{ currentWeek }}周</span>
									</div>
									<el-button type="primary" size="large" @click="nextWeek"
										class="rounded-full px-6 hover:shadow-md transition-shadow">
										下一周<el-icon class="ml-2">
											<ArrowRight />
										</el-icon>
									</el-button>
								</div>
							</div>
						</div>

						<div class="p-8 overflow-x-auto">
							<!-- 新建课程按钮 -->
							<div class="mb-6 text-right">
								<el-button type="primary" size="default" @click="handleAddCourse"
									class="rounded-full px-6 bg-gradient-to-r from-blue-500 to-indigo-600 hover:from-blue-600 hover:to-indigo-700 transition-all">
									<el-icon class="mr-2">
										<Plus />
									</el-icon>新建课程
								</el-button>
							</div>

							<!-- 课程表 -->
							<div class="grid grid-cols-1 lg:grid-cols-5 gap-6">
								<div v-for="(schedule, index) in weeklySchedule" :key="index" class="lg:col-span-1">
									<div
										class="bg-gradient-to-br from-white to-gray-50 rounded-3xl p-6 shadow-lg border border-gray-200">
										<div class="text-center mb-4">
											<h3 class="text-xl font-bold text-gray-800">{{ schedule.weekday }}</h3>
										</div>
										<!-- 上午 -->
										<div v-if="schedule.morning"
											class="mb-4 p-4 bg-blue-50 rounded-2xl border border-blue-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-blue-500 rounded-full"></div>
												<span class="text-sm font-medium text-blue-700">上午</span>
											</div>
											<div class="text-xs text-blue-600 mb-1">{{ schedule.morning.time }}</div>
											<div class="text-base font-bold text-gray-900 mb-1">
												{{ schedule.morning.course }}
											</div>
											<div class="text-xs text-gray-600 mb-2">{{ schedule.morning.courseType }} ·
												{{ schedule.morning.room }} · {{ schedule.morning.lecturer }}
											</div>
											<span
												class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium"
												:class="{
                              'bg-green-100 text-green-800': schedule.morning.status === 'completed',
                              'bg-yellow-100 text-yellow-800': schedule.morning.status === 'ongoing',
                              'bg-gray-100 text-gray-800': schedule.morning.status === 'upcoming'
                            }">
												{{ schedule.morning.status === 'completed' ? '已完成' : schedule.morning.status === 'ongoing' ? '进行中' : '即将开始' }}
											</span>
											<!-- 编辑按钮 -->
											<el-button type="text" size="small"
												@click="handleEditCourse(schedule.morning, schedule.weekday, '上午')"
												class="mt-2 text-blue-600 hover:text-blue-800 p-0">
												<el-icon class="mr-1">
													<Edit />
												</el-icon>编辑
											</el-button>
										</div>
										<div v-else class="mb-4 p-4 bg-gray-50 rounded-2xl border border-gray-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-gray-400 rounded-full"></div>
												<span class="text-sm font-medium text-gray-600">上午</span>
											</div>
											<div class="text-center py-2 text-gray-500">无课程安排</div>
										</div>

										<!-- 下午 -->
										<div v-if="schedule.afternoon"
											class="p-4 bg-green-50 rounded-2xl border border-green-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-green-500 rounded-full"></div>
												<span class="text-sm font-medium text-green-700">下午</span>
											</div>
											<div class="text-xs text-green-600 mb-1">{{ schedule.afternoon.time }}</div>
											<div class="text-base font-bold text-gray-900 mb-1">
												{{ schedule.afternoon.course }}
											</div>
											<div class="text-xs text-gray-600 mb-2">{{ schedule.afternoon.courseType }}
												· {{ schedule.afternoon.room }} · {{ schedule.afternoon.lecturer }}
											</div>
											<span
												class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium"
												:class="{
                              'bg-green-100 text-green-800': schedule.afternoon.status === 'completed',
                              'bg-yellow-100 text-yellow-800': schedule.afternoon.status === 'ongoing',
                              'bg-gray-100 text-gray-800': schedule.afternoon.status === 'upcoming'
                            }">
												{{ schedule.afternoon.status === 'completed' ? '已完成' : schedule.afternoon.status === 'ongoing' ? '进行中' : '即将开始' }}
											</span>
											<!-- 编辑按钮 -->
											<el-button type="text" size="small"
												@click="handleEditCourse(schedule.afternoon, schedule.weekday, '下午')"
												class="mt-2 text-green-600 hover:text-green-800 p-0">
												<el-icon class="mr-1">
													<Edit />
												</el-icon>编辑
											</el-button>
										</div>
										<div v-else class="p-4 bg-gray-50 rounded-2xl border border-gray-200">
											<div class="flex items-center gap-2 mb-2">
												<div class="w-3 h-3 bg-gray-400 rounded-full"></div>
												<span class="text-sm font-medium text-gray-600">下午</span>
											</div>
											<div class="text-center py-2 text-gray-500">无课程安排</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>

					<!-- 课程任务 -->
					<div class="bg-white rounded-3xl shadow-xl border border-gray-200 overflow-hidden">
						<div
							class="px-8 py-6 border-b border-gray-200 bg-gradient-to-r from-green-50 to-emerald-50 flex items-center gap-4">
							<div
								class="w-16 h-16 bg-gradient-to-br from-green-500 to-emerald-600 rounded-2xl flex items-center justify-center">
								<el-icon class="text-white text-2xl">
									<List />
								</el-icon>
							</div>
							<div>
								<h3 class="text-3xl font-bold text-gray-900">今日任务</h3>
								<p class="text-green-600 text-xl">系统时间: {{ currentTime }}</p>
							</div>
						</div>
						<div class="p-8">
							<div class="grid grid-cols-2 md:grid-cols-3 gap-8">
								<div v-for="task in courseTasks" :key="task.id" @click="handleTask(task)"
									class="group flex flex-col items-center p-8 border-2 border-gray-100 rounded-2xl hover:border-indigo-300 hover:bg-indigo-50 transition-all duration-300 cursor-pointer transform hover:scale-105 active:scale-95">
									<div
										class="w-20 h-20 bg-gradient-to-br from-indigo-400 to-purple-500 rounded-2xl flex items-center justify-center mb-4 group-hover:shadow-lg transition-shadow">
										<el-icon class="text-white text-3xl">
											<component :is="task.icon" />
										</el-icon>
									</div>
									<span
										class="text-lg text-gray-700 font-medium group-hover:text-indigo-600 transition-colors">{{ task.name }}</span>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 课程表单弹窗 -->
		<el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑课程' : '新建课程'" width="600px"
			:before-close="handleClose">
			<el-form :model="courseForm" ref="courseFormRef" label-width="120px" :rules="formRules">
				<el-form-item label="星期" prop="weekday">
					<el-select v-model="courseForm.weekday" placeholder="请选择星期">
						<el-option label="星期一" value="星期一"></el-option>
						<el-option label="星期二" value="星期二"></el-option>
						<el-option label="星期三" value="星期三"></el-option>
						<el-option label="星期四" value="星期四"></el-option>
						<el-option label="星期五" value="星期五"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="时间段" prop="times">
					<el-select v-model="courseForm.times" placeholder="请选择时间段">
						<el-option label="上午" value="上午"></el-option>
						<el-option label="下午" value="下午"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上课时间" prop="classTimeOn">
					<el-time-picker v-model="courseForm.classTimeOn" format="HH:mm" value-format="HH:mm"
						placeholder="选择上课时间">
					</el-time-picker>
				</el-form-item>
				<el-form-item label="下课时间" prop="classTimeEnd">
					<el-time-picker v-model="courseForm.classTimeEnd" format="HH:mm" value-format="HH:mm"
						placeholder="选择下课时间">
					</el-time-picker>
				</el-form-item>
				<el-form-item label="班级编号" prop="classId">
					<el-input v-model="courseForm.classId" placeholder="请输入班级编号"></el-input>
				</el-form-item>
				<el-form-item label="课程名" prop="course">
					<el-input v-model="courseForm.course" placeholder="请输入课程名"></el-input>
				</el-form-item>
				<el-form-item label="讲师" prop="lecturer">
					<el-input v-model="courseForm.lecturer" placeholder="请输入讲师"></el-input>
				</el-form-item>
				<el-form-item label="日期数字" prop="dateDay">
					<el-input v-model="courseForm.dateDay" placeholder="如：901（9月1日）"></el-input>
				</el-form-item>
				<el-form-item label="上课日期" prop="date">
					<el-date-picker v-model="courseForm.date" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
						placeholder="选择日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="教室" prop="classRoom">
					<el-input v-model="courseForm.classRoom" placeholder="请输入教室"></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">确认</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		computed,
		ref,
		onMounted,
		watch,
		reactive,
		toRefs,
		getCurrentInstance
	} from 'vue'
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		mockClassList
	} from '@/mock/classData'
	import {
		ElMessage,
		ElLoading,
		ElForm,
		ElFormItem,
		ElInput,
		ElSelect,
		ElOption,
		ElTimePicker,
		ElDatePicker,
		ElDialog,
		ElButton
	} from 'element-plus'
	import {
		ArrowLeft,
		ArrowRight,
		Reading,
		Files,
		VideoPlay,
		Notebook,
		Document,
		User,
		UserFilled,
		Calendar,
		List,
		Plus,
		Edit
	} from '@element-plus/icons-vue'
	import axios from 'axios'

	// 创建axios实例，指向后端Teacher服务的API
	const api = axios.create({
		baseURL: 'http://localhost:8088/api', // 显示课程表后端接口
		timeout: 5000
	})

	// 创建课程管理API实例（9002端口）
	const courseApi = axios.create({
		baseURL: 'http://localhost:9002', // 课程编辑和新建接口
		timeout: 5000
	})

	const route = useRoute()
	const router = useRouter()
	const {
		proxy
	} = getCurrentInstance()

	// 课程表单相关
	const dialogVisible = ref(false)
	const isEditMode = ref(false)
	const courseFormRef = ref(null)

	// 表单数据
	const courseForm = reactive({
		id: null,
		weekday: '',
		times: '',
		classTimeOn: '',
		classTimeEnd: '',
		classId: '',
		course: '',
		lecturer: '',
		dateDay: '',
		date: '',
		classRoom: ''
	})

	// 表单验证规则
	const formRules = reactive({
		weekday: [{
			required: true,
			message: '请选择星期',
			trigger: 'change'
		}],
		times: [{
			required: true,
			message: '请选择时间段',
			trigger: 'change'
		}],
		classTimeOn: [{
			required: true,
			message: '请选择上课时间',
			trigger: 'change'
		}],
		classTimeEnd: [{
			required: true,
			message: '请选择下课时间',
			trigger: 'change'
		}],
		classId: [{
			required: true,
			message: '请输入班级编号',
			trigger: 'blur'
		}],
		course: [{
			required: true,
			message: '请输入课程名',
			trigger: 'blur'
		}],
		lecturer: [{
			required: true,
			message: '请输入讲师',
			trigger: 'blur'
		}],
		dateDay: [{
			required: true,
			message: '请输入日期数字',
			trigger: 'blur'
		}],
		date: [{
			required: true,
			message: '请选择上课日期',
			trigger: 'change'
		}],
		classRoom: [{
			required: true,
			message: '请输入教室',
			trigger: 'blur'
		}]
	})

	const classId = computed(() => Number(route.params.id))
	const classInfo = computed(() => mockClassList.find(c => c.id === classId.value))

	// 课程相关数据
	const curriculumList = ref([]) // 确保初始化为数组
	const courseCount = ref(0)

	const getFirstChar = (text) => {
		if (!text) return '班'
		return text.trim().charAt(0).toUpperCase()
	}

	const goBack = () => router.back()
	const goToStudy = () => router.push('/study')
	const goToResources = () => router.push('/resources')

	const courseTasks = ref([{
			id: 1,
			name: '直播',
			icon: VideoPlay
		},
		{
			id: 2,
			name: '发布作业',
			icon: Notebook
		},
		{
			id: 3,
			name: '知识点',
			icon: Reading
		},
		{
			id: 4,
			name: '教学案例',
			icon: Files
		},
		{
			id: 5,
			name: '作业评价',
			icon: Document
		},
		{
			id: 6,
			name: '看视频',
			icon: VideoPlay
		}
	])

	const handleTask = (task) => {
		switch (task.name) {
			case '直播':
				ElMessage.info('直播由后端实现，这里先占位')
				break
			case '发布作业':
				router.push(`/class/${classId.value}/homework`)
				break
			case '知识点':
				ElMessage.success('知识点入口占位')
				break
			case '教学案例':
				ElMessage.success('教学案例入口占位')
				break
			case '作业评价':
				ElMessage.success('作业评价入口占位')
				break
			case '看视频':
				ElMessage.success('看视频入口占位')
				break
		}
	}

	const currentTime = ref('')
	const currentWeek = ref(1)
	const currentWeekOffset = ref(0)

	const formatDate = (d) => {
		const y = d.getFullYear()
		const m = String(d.getMonth() + 1).padStart(2, '0')
		const day = String(d.getDate()).padStart(2, '0')
		return `${y}-${m}-${day}`
	}

	const getWeekRange = (offset) => {
		const now = new Date()
		const day = now.getDay() || 7
		const monday = new Date(now)
		monday.setDate(now.getDate() - day + 1 + offset * 7)
		const sunday = new Date(monday)
		sunday.setDate(monday.getDate() + 6)
		return `${formatDate(monday)} ~ ${formatDate(sunday)}`
	}

	const currentWeekRange = computed(() => getWeekRange(currentWeekOffset.value))

	// 从数据库数据构建课程表
	const buildWeeklySchedule = () => {
		const weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五']
		// 按星期几初始化课程表结构
		const schedule = weekdays.map(weekday => ({
			id: weekday,
			weekday,
			morning: null,
			afternoon: null
		}))

		// 填充数据库课程数据
		curriculumList.value.forEach(item => {
			// 找到对应星期几的位置
			const dayIndex = weekdays.indexOf(item.date);
			if (dayIndex === -1) return;

			// 构建课程信息
			const courseInfo = {
				id: item.id,
				course: item.course,
				courseType: item.times === '上午' ? '理论课' : '实战课',
				room: item.classRoom || item.class_room, // 兼容两种字段格式
				time: `${item.classTimeOn || item.class_time_on} ~ ${item.classTimeEnd || item.class_time_end}`, // 兼容两种字段格式
				lecturer: item.lecturer,
				status: getCourseStatus(item.classTimeOn || item.class_time_on, item.classTimeEnd || item
					.class_time_end),
				classTimeOn: item.classTimeOn || item.class_time_on,
				classTimeEnd: item.classTimeEnd || item.class_time_end,
				dateDay: item.dateDay,
				classId: item.classId
			}

			// 填充上午/下午课程
			if (item.times === '上午') {
				schedule[dayIndex].morning = courseInfo
			} else if (item.times === '下午') {
				schedule[dayIndex].afternoon = courseInfo
			}
		})

		return schedule
	}

	// 计算课程状态
	const getCourseStatus = (startTime, endTime) => {
		const now = new Date()
		const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())

		// 解析课程时间
		if (!startTime || !endTime) return 'upcoming';

		const [startHours, startMinutes] = startTime.split(':').map(Number)
		const [endHours, endMinutes] = endTime.split(':').map(Number)

		const start = new Date(today)
		start.setHours(startHours, startMinutes)

		const end = new Date(today)
		end.setHours(endHours, endMinutes)

		if (now > end) {
			return 'completed'
		} else if (now >= start && now <= end) {
			return 'ongoing'
		} else {
			return 'upcoming'
		}
	}

	const weeklySchedule = computed(() => buildWeeklySchedule())

	const prevWeek = () => {
		currentWeekOffset.value -= 1
		currentWeek.value = Math.max(1, currentWeek.value - 1)
	}

	const nextWeek = () => {
		currentWeekOffset.value += 1
		currentWeek.value = currentWeek.value + 1
	}

	const updateTime = () => {
		currentTime.value = new Date().toLocaleString('zh-CN')
	}

	// 获取课程数据 - 简化处理逻辑，确保能显示数据
	const fetchCurriculum = async () => {
		const loading = ElLoading.service({
			lock: true,
			text: '加载课程信息中...',
			background: 'rgba(255, 255, 255, 0.7)'
		})

		try {
			// 调用后端API获取课程数据
			console.log(`请求课程数据: /curriculum/class/${classId.value}`);
			const response = await api.get(`/curriculum/class/${classId.value}`);

			// 直接使用响应数据，不做过多格式判断
			if (response && response.data) {
				// 后端返回的是数组直接使用
				curriculumList.value = Array.isArray(response.data) ? response.data : [];
				courseCount.value = curriculumList.value.length;
				console.log('获取到的课程数据:', curriculumList.value);

				// 显示获取到的课程数量
				ElMessage.success(`成功加载 ${courseCount.value} 门课程`);
			} else {
				curriculumList.value = [];
				courseCount.value = 0;
				ElMessage.warning('未获取到课程数据');
			}

		} catch (error) {
			console.error('获取课程数据失败:', error);
			ElMessage.error(`获取课程失败: ${error.message || '请检查后端服务是否运行'}`);
			curriculumList.value = [];
			courseCount.value = 0;
		} finally {
			loading.close();
		}
	}

	// 打开新建课程弹窗
	const handleAddCourse = () => {
		isEditMode.value = false
		// 重置表单
		Object.keys(courseForm).forEach(key => {
			courseForm[key] = ''
		})
		// 默认填充班级ID
		courseForm.classId = classId.value.toString()
		dialogVisible.value = true
	}

	// 打开编辑课程弹窗
	const handleEditCourse = (course, weekday, times) => {
		isEditMode.value = true
		// 填充表单数据
		courseForm.id = course.id
		courseForm.weekday = weekday
		courseForm.times = times
		courseForm.classTimeOn = course.classTimeOn
		courseForm.classTimeEnd = course.classTimeEnd
		courseForm.classId = course.classId.toString()
		courseForm.course = course.course
		courseForm.lecturer = course.lecturer
		courseForm.dateDay = course.dateDay.toString()
		courseForm.classRoom = course.room
		dialogVisible.value = true
	}

	// 关闭弹窗
	const handleClose = () => {
		dialogVisible.value = false
		if (courseFormRef.value) {
			courseFormRef.value.resetFields()
		}
	}

	// 提交表单
	const submitForm = async () => {
		if (!courseFormRef.value) return

		try {
			await courseFormRef.value.validate()

			// 准备提交的数据
			const submitData = {
				...courseForm
			}
			// 转换数字类型
			submitData.classId = Number(submitData.classId)
			submitData.dateDay = Number(submitData.dateDay)

			const loading = ElLoading.service({
				lock: true,
				text: isEditMode.value ? '正在更新课程...' : '正在创建课程...',
				background: 'rgba(255, 255, 255, 0.7)'
			})

			try {
				if (isEditMode.value) {
					// 调用更新接口
					await courseApi.post('/course/update', submitData)
					ElMessage.success('课程更新成功')
				} else {
					// 调用新增接口
					await courseApi.post('/course/add', submitData)
					ElMessage.success('课程创建成功')
				}

				// 关闭弹窗
				dialogVisible.value = false
				// 重新加载课程数据
				fetchCurriculum()
			} catch (error) {
				console.error(isEditMode.value ? '更新课程失败' : '创建课程失败', error)
				ElMessage.error(
					`${isEditMode.value ? '更新课程' : '创建课程'}失败: ${error.response?.data?.message || error.message}`
					)
			} finally {
				loading.close()
			}
		} catch (error) {
			console.error('表单验证失败', error)
			return false
		}
	}

	onMounted(() => {
		updateTime();
		setInterval(updateTime, 1000);
		fetchCurriculum(); // 加载课程数据
	})

	// 监听班级ID变化，重新加载课程
	watch(classId, () => {
		fetchCurriculum();
	})
</script>

<style scoped>
	@keyframes blob {
		0% {
			transform: translate(0px, 0px) scale(1);
		}

		33% {
			transform: translate(30px, -50px) scale(1.1);
		}

		66% {
			transform: translate(-20px, 20px) scale(0.9);
		}

		100% {
			transform: translate(0px, 0px) scale(1);
		}
	}

	.animate-blob {
		animation: blob 7s infinite;
	}

	.animation-delay-2000 {
		animation-delay: 2s;
	}

	.animation-delay-4000 {
		animation-delay: 4s;
	}

	/* DNA 双螺旋动画 */
	.helix-container {
		position: relative;
		width: 220px;
		height: 180px;
		perspective: 600px;
		transform-style: preserve-3d;
	}

	.helix-row {
		position: relative;
		width: 100%;
		height: 18px;
		display: flex;
		align-items: center;
		justify-content: center;
		animation: helix-rise 4s linear infinite;
		animation-delay: calc(var(--i) * -0.2s);
	}

	.helix-dot {
		width: 12px;
		height: 12px;
		border-radius: 9999px;
		display: inline-block;
	}

	.helix-dot.left {
		background: radial-gradient(circle at 30% 30%, #60a5fa, #2563eb);
		transform: translateX(-70px) translateZ(-20px);
		box-shadow: 0 6px 16px rgba(37, 99, 235, 0.35);
	}

	.helix-dot.right {
		background: radial-gradient(circle at 30% 30%, #34d399, #059669);
		transform: translateX(70px) translateZ(20px);
		box-shadow: 0 6px 16px rgba(5, 150, 105, 0.35);
	}

	@keyframes helix-rise {
		0% {
			transform: translateY(120px) rotateY(0deg);
		}

		50% {
			transform: translateY(60px) rotateY(180deg);
		}

		100% {
			transform: translateY(0) rotateY(360deg);
		}
	}
</style>